package com.vca.service.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.vca.common.constants.Constants;
import com.vca.common.model.system.SystemAttachment;
import com.vca.common.request.PageParamRequest;
import com.vca.common.request.SystemAttachmentMoveRequest;
import com.vca.common.request.SystemAttachmentRequest;
import com.vca.common.utils.VcaUtil;
import com.vca.service.dao.system.SystemAttachmentDao;
import com.vca.service.service.SystemAttachmentService;
import com.vca.service.service.SystemConfigService;
import com.vca.service.util.OssUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * SystemAttachmentServiceImpl 接口实现
 */
@Service
@Slf4j
public class SystemAttachmentServiceImpl extends ServiceImpl<SystemAttachmentDao, SystemAttachment> implements SystemAttachmentService {

    public static final Logger logger = LoggerFactory.getLogger(SystemAttachmentServiceImpl.class);

    @Resource
    private SystemAttachmentDao dao;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private OssUtils ossUtils;

    /**
     * 同步到云服务， 更新图片上传类型
     *
     * @param attId Integer 主键id
     * @param type  int 图片上传类型 1本地 2七牛云 3OSS 4COS
     */
    @Override
    public void updateCloudType(Integer attId, int type) {
        SystemAttachment systemAttachment = new SystemAttachment();
        systemAttachment.setAttId(attId);
        systemAttachment.setImageType(type);
        updateById(systemAttachment);
    }

    /**
     * 附件分页
     *
     * @param pid              Integer pid
     * @param pageParamRequest PageParamRequest 分页参数
     * @return List<SystemAttachment>
     */
    @Override
    public List<SystemAttachment> getList(Integer pid, String attType, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<SystemAttachment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemAttachment::getPid, pid);
        if (StringUtils.isNotEmpty(attType)) {
            lambdaQueryWrapper.in(SystemAttachment::getAttType, StringUtils.split(attType, ","));
        }
        lambdaQueryWrapper.orderByDesc(SystemAttachment::getAttId);
        return dao.selectList(lambdaQueryWrapper);
    }

    /**
     * 给图片加前缀
     *
     * @param path String 路径
     * @return String
     */
    @Override
    public String prefixImage(String path) {
//        String ossFileUrl = OssUtils.getOssFileUrl(path);
        // 如果那些域名不需要加，则跳过
        int strCount = findStrCount(path, Constants.UPLOAD_TYPE_IMAGE + "/", 0);
        logger.info("data中包含’" + Constants.UPLOAD_TYPE_IMAGE + "/‘的数量是：" + strCount);
        String a = path;
        int vcaImageIndex = 0;
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < strCount; i++) {
            if (i == 0) {
                vcaImageIndex = a.indexOf(Constants.UPLOAD_TYPE_IMAGE + "/");
            } else {
                vcaImageIndex = a.indexOf(Constants.UPLOAD_TYPE_IMAGE + "/", vcaImageIndex + i);
            }
            System.out.println("vcaImageIndex = " + vcaImageIndex);
            if (vcaImageIndex == -1) {
                continue;
            }
            String substring = a.substring(vcaImageIndex, a.length());

            int i2 = substring.indexOf("\"");
            if (substring.substring(i2 - 1, i2).equals("\\")) {
                i2 -= 1;
            }
            a = path;
            String substring1 = a.substring(vcaImageIndex, i2 + vcaImageIndex);
            // TODO: 2022/12/27 如果输入的链接是内网的Endpoint，那么就切换成公网的
            String imagePath = ossUtils.getOssFileUrl(substring1);
            map.put(substring1, imagePath);
        }
        for (String key : map.keySet()) {
            path = path.replace(key, map.get(key));
        }
        return path.replace("-internal.aliyuncs.com",".aliyuncs.com");
//        return path.replace(Constants.UPLOAD_TYPE_IMAGE+"/", getCdnUrl() + "/"+ Constants.UPLOAD_TYPE_IMAGE+"/");
    }


    public static void main(String[] args) {
        String aa = "\\";
        System.out.println("aa = " + aa);
    }

    /**
     * 查询字符串中指定字符个数
     *
     * @param oriStr  原字符串
     * @param findStr 需要查找的字符
     * @param count   固定值：0
     * @return 查找到字符的个数
     */
    public static int findStrCount(String oriStr, String findStr, int count) {

        if (oriStr.contains(findStr)) {
            count++;
            count = findStrCount(oriStr.substring(oriStr.indexOf(findStr) + findStr.length()), findStr, count);
        }
        return count;
    }


    /**
     * 给文件加前缀
     *
     * @param path String 路径
     * @return String
     */
    @Override
    public String prefixFile(String path) {
        int strCount = findStrCount(path, Constants.UPLOAD_TYPE_FILE + "/", 0);
        logger.info("data中包含’" + Constants.UPLOAD_TYPE_FILE + "/‘的数量是：" + strCount);
        String a = path;
        int vcaImageIndex = 0;
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < strCount; i++) {
            if (i == 0) {
                vcaImageIndex = a.indexOf(Constants.UPLOAD_TYPE_FILE + "/");
            } else {
                vcaImageIndex = a.indexOf(Constants.UPLOAD_TYPE_FILE + "/", vcaImageIndex + i);
            }
            System.out.println("vcaImageIndex = " + vcaImageIndex);
            if (vcaImageIndex == -1) {
                continue;
            }
            String substring = a.substring(vcaImageIndex, a.length());

            int i2 = substring.indexOf("\"");
            if (substring.substring(i2 - 1, i2).equals("\\")) {
                i2 -= 1;
            }
            a = path;
            String substring1 = a.substring(vcaImageIndex, i2 + vcaImageIndex);
            logger.info("substring1--->{}",substring1);
            // TODO: 2022/12/27 如果输入的链接是内网的Endpoint，那么就切换成公网的
            String imagePath = ossUtils.getOssFileUrl(substring1);
            logger.info("imagePath--->{}",imagePath);
            map.put(substring1, imagePath);
        }
        for (String key : map.keySet()) {
            path = path.replace(key, map.get(key));
        }
        return path.replace("-internal.aliyuncs.com",".aliyuncs.com");
    }

    @Override
    public String prefixFileCopy(String path) {
        if (path.contains("file/excel")) {
            String cdnUrl = systemConfigService.getValueByKey("local" + "UploadUrl");
            return path.replace("vcaImage/file/", cdnUrl + "vcaImage/file/");
        }
        return path.replace("file/", getCdnUrl() + "/file/");
    }

    /**
     * 获取cdn url
     *
     * @return String
     */
    private String getCdnUrl() {
//        return asyncService.getCurrentBaseUrl();
        String uploadType = systemConfigService.getValueByKeyException("uploadType");
        //获取配置信息
        int type = Integer.parseInt(uploadType);
        String pre = "local";
        switch (type) {
            case 2:
                pre = "qn";
                break;
            case 3:
                pre = "al";
                break;
            case 4:
                pre = "tx";
                break;
            default:
                break;
        }
        return systemConfigService.getValueByKey(pre + "UploadUrl");
    }

    /**
     * 清除 cdn url， 在保存数据的时候使用
     *
     * @param path String 文件路径
     * @return String
     */
    @Override
    public String clearPrefix(String path) {
        if (StringUtils.isBlank(path)) {
            return path;
        }
        int c = path.indexOf(Constants.UPLOAD_TYPE_IMAGE);
        if (c==-1){
            c = path.indexOf(Constants.UPLOAD_TYPE_FILE);
            if (c==-1) {
                return path;
            }
        }
        String p=path.substring(0,c);
        path=path.substring(c,path.length());
        Constants.CND_URL = getCdnUrl();
        String alUrl = systemConfigService.getValueByKey("alUrl");
        //去除阿里云前缀
        if (path.contains(alUrl+"/")||p.contains(alUrl+"/")){
            path = path.replace(alUrl + "/", "");
            p = p.replace(alUrl + "/", "");
        }
        if (path.contains(getCdnUrl() + "/")||p.contains(getCdnUrl() + "/")) {
            path = path.replace(getCdnUrl() + "/", "");
            p = p.replace(alUrl + "/", "");
        }
        path = p+path;
        //判断是否为轮播图
        if(!path.contains("[")){
            //获取图片 后缀之前的
            int indexOf = path.indexOf("?");
            if (indexOf!=-1){
                path=path.substring(0,indexOf);
            }
            return path;
        }
        String s = this.clearImagePrefix(path);
        path=this.clearFilePrefix(s);
        return path;
    }

    public String clearImagePrefix(String path){
        //判断阿里云 sts后缀是否去掉
        int number =0;
        if (path.contains("?")){
            number = appearNumber(path,"?");
        }
        int indexOf =0;

        for (int i = 0; i < number; i++) {
            if (path.contains(Constants.UPLOAD_TYPE_IMAGE)){
                //取出 path
                String s = path;
                //获取图片所在下标
                if (i == 0) {
                    indexOf = s.indexOf(Constants.UPLOAD_TYPE_IMAGE + "/");
                } else {
                    indexOf = s.indexOf(Constants.UPLOAD_TYPE_IMAGE + "/", indexOf + i);
                }
                if (indexOf==-1){
                    return path;
                }
                //截取图片以后的字符
                String substring = s.substring(indexOf, s.length());
                //获取 "所在下标
                int i2 = substring.indexOf("\"");
                if (substring.substring(i2 - 1, i2).equals("\\")) {
                    i2 -= 1;
                }
                //去除其他路径 只获取图片路径
                String substring1 = s.substring(indexOf, i2 + indexOf);
                logger.info("substring1--->{}",substring1);
                if (substring1.contains("?")){
                    //获取 后缀所在下标
                    int index = substring1.indexOf("?");
                    //去除 后缀
                    substring1=substring1.substring(index,i2);
                    path = path.replace(substring1, "");
                }
            }
        }
        return path;
    }

    public String clearFilePrefix(String path){
        //判断阿里云 sts后缀是否去掉
        int number =0;
        if (path.contains("?")){
            number = appearNumber(path,"?");
        }
        int indexOf =0;
        for (int i = 0; i < number; i++) {
            if (path.contains(Constants.UPLOAD_TYPE_FILE)){
                //取出 path
                String s = path;
                //获取图片所在下标
                if (i == 0) {
                    indexOf = s.indexOf(Constants.UPLOAD_TYPE_FILE + "/");
                } else {
                    indexOf = s.indexOf(Constants.UPLOAD_TYPE_FILE + "/", indexOf + i);
                }
                if (indexOf==-1){
                    return path;
                }
                //截取图片以后的字符
                String substring = s.substring(indexOf, s.length());
                //获取 "所在下标
                int i2 = substring.indexOf("\"");
                if (substring.charAt(i2 - 1) == '\\') {
                    i2 -= 1;
                }
                //去除其他路径 只获取图片路径
                String substring1 = s.substring(indexOf, i2 + indexOf);
                logger.info("substring1--->{}",substring1);
                if (substring1.contains("?")){
                    //获取 后缀所在下标
                    int index = substring1.indexOf("?");
                    //去除 后缀
                    substring1=substring1.substring(index,i2);
                    path = path.replace(substring1, "");
                }
            }
        }
        return path;
    }

    /**
     * public int indexOf(int ch, int fromIndex)
     * 返回在此字符串中第一次出现指定字符处的索引，从指定的索引开始搜索
     *
     * @param srcText
     * @param findText
     * @return
     */
    private int appearNumber(String srcText, String findText) {
        int count = 0;
        int index = 0;
        while ((index = srcText.indexOf(findText, index)) != -1) {
            index = index + findText.length();
            count++;
        }
        return count;
    }

    /**
     * 新增附件
     *
     * @param systemAttachmentRequest 新增参数
     */
    @Override
    public Boolean add(SystemAttachmentRequest systemAttachmentRequest) {
        SystemAttachment systemAttachment = new SystemAttachment();
        BeanUtils.copyProperties(systemAttachmentRequest, systemAttachment);
        return save(systemAttachment);
    }

    /**
     * 编辑附件
     *
     * @param systemAttachmentRequest 更新参数
     */
    @Override
    public Boolean edit(SystemAttachmentRequest systemAttachmentRequest) {
        SystemAttachment systemAttachment = new SystemAttachment();
        BeanUtils.copyProperties(systemAttachmentRequest, systemAttachment);
        return updateById(systemAttachment);
    }

    /**
     * 更改图片目录
     *
     * @param move 参数
     */
    @Override
    public Boolean updateAttrId(SystemAttachmentMoveRequest move) {
        LambdaUpdateWrapper<SystemAttachment> lup = new LambdaUpdateWrapper<>();
        lup.in(SystemAttachment::getAttId, VcaUtil.stringToArray(move.getAttrId()));
        lup.set(SystemAttachment::getPid, move.getPid());
        return update(lup);
    }
}

